package ar.activity;

import java.util.ArrayList;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import ar.Location.Constant.Define;
import ar.Location.Helper.BitmapProvider;
import ar.Location.Map.MapOverlay;
import ar.Location.Map.MyOverlayItem;
import ar.Location.PlaceObject.Place;
import ar.Location.PlaceObject.PlaceCategory;
import ar.Location.PlaceObject.PlaceCategoryManager;
import ar.Location.UI.ListPlaceResultAdapter;
import ar.activity.R.string;
import ar.camera.pojo.GeoLocation;
import ar.globals.Globals;

import com.google.android.maps.GeoPoint;

public class ListPlaceResultActivity extends BaseActivity {

	private static final String TAG = "listResultsActivity";
	ListView listView = null;
	PlaceCategory placeCategory = null;
	OnItemClickListener onItemClick = null;
	ListPlaceResultAdapter listViewAdapter = null;
	Handler handlerUpdateThumbImage = null;
	ArrayList<Bitmap> listThumbImages = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.list_place_result);
		super.onCreate(savedInstanceState);
		tvWhatScreen.setText(res.getString(string.resultScreenName));

		initPlaceCategory();

		if (placeCategory != null) {
			if (placeCategory.count() == 0) {
				setContentView(R.layout.place_no_data_layout);
			} else {
				initListThumbImages();
				initAdapter();
				initHandlerUpdateThumbImage();
				initEventOnItemClick();
				initView();
			}
		} else {
			setContentView(R.layout.place_no_data_layout);
		}
	}

	
	Menu men = null;
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		men = menu;
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.list_results_menu, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuItem menuItemShowCam = menu.findItem(R.id.menuShowOnCam);
		MenuItem menuItemShowMap = menu.findItem(R.id.menuShowOnMap);
		menuItemShowCam.setTitle(res.getString(string.menuTitleShowOnCam));
		menuItemShowMap.setTitle(res.getString(string.menuTitleShowOnMap));
		return super.onPrepareOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		int menuId = item.getItemId();
		switch (menuId) {
		case R.id.menuShowOnCam:
			bindOnCam();
			return true;
		case R.id.menuShowOnMap:
			bindOnMap();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}	

	private void bindOnCam() {
		if (placeCategory != null && placeCategory.count() > 0) {
			Globals.listOfGeoLocations = new ArrayList<GeoLocation>();
			ArrayList<Place> listResults = placeCategory.listPlaceResult;

			if (listResults != null) {
				Globals.markers.clear();
				MapOverlay.mPoints.clear();

				for (int i = 0; i < listResults.size(); i++) {
					Place place = listResults.get(i);
					if (place.latitude != null && place.longitude != null) {
						if (place.latitude.length() > 0
								&& place.longitude.length() > 0) {
							float lat = Float.parseFloat(place.latitude);
							float lng = Float.parseFloat(place.longitude);
							
							int latitude = (int) (lat * 1E6);
							int longitude = (int) (lng * 1E6);
							GeoPoint point = new GeoPoint(latitude, longitude);
							MyOverlayItem myOverlay = new MyOverlayItem(point,
									place.name, place.address);
							myOverlay.updateInfoFrom(place);
							Globals.markers.add(myOverlay);
							
							GeoLocation geo = new GeoLocation(lat, lng,
									place.name);
							Globals.listOfGeoLocations.add(geo);
						}
					}
				}
			}

			if (Globals.locationIconView != null)
				Globals.locationIconView.getmRenderer().setmListOfGeoLocations(
						Globals.listOfGeoLocations);
			if (Globals.compassView != null)
				Globals.compassView.getmRenderer().setmListOfGeoLocations(
						Globals.listOfGeoLocations);
			Intent i = new Intent(getApplicationContext(),
					ARCameraActivity.class);
			startActivity(i);

			finish();
		}

	}

	private void bindOnMap() {
		// TODO Auto-generated method stub
		if (placeCategory != null && placeCategory.count() > 0) {
			final ArrayList<Place> listResults = placeCategory.listPlaceResult;

			if (listResults != null && listResults.size() > 0) {

				final int size = listResults.size();

				Globals.markers.clear();
				MapOverlay.mPoints.clear();

				for (int i = 0; i < size; i++) {
					Place place = listResults.get(i);
					if (place.latitude != null && place.longitude != null) {
						if (place.latitude.length() > 0
								&& place.longitude.length() > 0) {
							float lat = Float.parseFloat(place.latitude);
							float lng = Float.parseFloat(place.longitude);
							int latitude = (int) (lat * 1E6);
							int longitude = (int) (lng * 1E6);
							GeoPoint point = new GeoPoint(latitude, longitude);
							MyOverlayItem myOverlay = new MyOverlayItem(point,
									place.name, place.address);
							myOverlay.updateInfoFrom(place);
							Globals.markers.add(myOverlay);
						}
					}
				}
			}
			Intent intent = new Intent(getApplicationContext(),
					ARMapActivity.class);
			intent.putExtra(Define.ACTION_OUTSIDE_MAP,
					Define.ACTION_SHOW_LIST_RESULTS);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			finish();
		}
	}

	private void initPlaceCategory() {
		// TODO Auto-generated method stub
		placeCategory = PlaceCategoryManager.currentPlaceCategory;
	}

	public void initEventOnItemClick() {
		onItemClick = new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub

				if (placeCategory != null) {
					Place place = placeCategory.getPlaceAtIndex(position);
					if (place != null) {
						PlaceCategory.currentPlace = place;
						Intent intent = new Intent(
								ListPlaceResultActivity.this,
								PlaceDetailActivity.class);
						startActivity(intent);
					}
				}
			}
		};
	}

	public void initAdapter() {
		listViewAdapter = new ListPlaceResultAdapter(this, listThumbImages);
	}

	public void initView() {
		listView = (ListView) findViewById(R.id.listPlaceResult);
		listView.setOnItemClickListener(onItemClick);
		listView.setAdapter(listViewAdapter);
	}

	private void initListThumbImages() {
		// TODO Auto-generated method stub
		if (placeCategory != null && placeCategory.count() > 0) {
			int nImages = placeCategory.count();
			listThumbImages = new ArrayList<Bitmap>();
			for (int i = 0; i < nImages; i++) {
				listThumbImages.add(null);
				final Place place = placeCategory.getPlaceAtIndex(i);
				final int index = i;
				Thread threadLoadImage = new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						Bitmap bmp = BitmapProvider
								.getBitmapFromURL(place.imageUrl);
						listThumbImages.set(index, bmp);
						if (handlerUpdateThumbImage != null) {
							handlerUpdateThumbImage.sendEmptyMessage(0);
						}
					}
				});
				threadLoadImage.start();
			}
		}
	}

	private void initHandlerUpdateThumbImage() {
		// TODO Auto-generated method stub
		handlerUpdateThumbImage = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				listViewAdapter.notifyDataSetChanged();
			}
		};
	}

	public void release() {
		if (listThumbImages != null && listThumbImages.size() > 0) {
			int nImages = listThumbImages.size();
			for (int i = 0; i < nImages; i++) {
				Bitmap bmp = listThumbImages.get(i);
				if (bmp != null) {
					Log.d(TAG, "Release bitmap at index: " + i);
					bmp.recycle();
				}
			}
		}
	}
	
	@Override
	protected void onUpdateUI() {
		// TODO Auto-generated method stub
		tvWhatScreen.setText(res.getString(string.resultScreenName));
		if(men != null) {
			onPrepareOptionsMenu(men);
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		release();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		finish();
	}
}
